package com.home766.util;

import com.allinpay.ets.client.RequestOrder;
import com.allinpay.ets.client.SecurityUtil;
import com.home766.dto.PaymentDTO;
import net.biz.entity.Order;
import net.biz.util.ParamsUtil;

public class PaymentUtil {
	public static void getParams(PaymentDTO dto,String requestType){
		String serverUrl=PropertyUtil.getValue("serverUrl");
		String payerIDCard=PropertyUtil.getValue("payerIDCard");
		String key=PropertyUtil.getValue("key");
		String version=PropertyUtil.getValue("version");
		String language=PropertyUtil.getValue("language");
		String inputCharset= PropertyUtil.getValue("inputCharset");
		String merchantId=PropertyUtil.getValue("merchantId");
		String pickupUrl=PropertyUtil.getValue("pickupUrl");
		if(!StringUtil.isNullOrSpace(requestType)){
			pickupUrl+=requestType;
		}
		String receiveUrl=PropertyUtil.getValue("receiveUrl");
//		receiveUrl+=token;
		String payType=PropertyUtil.getValue("payType");
		String signType=PropertyUtil.getValue("signType");
		String orderNo=dto.getOrderNo();
		String orderAmount=dto.getOrderAmount();
		String orderDatetime=dto.getOrderDatetime();
		String orderCurrency=PropertyUtil.getValue("orderCurrency");
		String orderExpireDatetime=dto.getOrderExpireDatetime();
		String payerTelephone=dto.getPayerTelephone();
		String payerEmail=dto.getPayerEmail();
		String payerName=dto.getPayerName();
		String pid=PropertyUtil.getValue("pid");
		String productName=dto.getProductName();
		String productId=PropertyUtil.getValue("productId");
		String productNum=dto.getProductNum();
		String productPrice=PropertyUtil.getValue("productPrice");
		String productDesc=dto.getProductDesc();
		String ext1=PropertyUtil.getValue("ext1");
		String ext2=PropertyUtil.getValue("ext2");
		String extTL=PropertyUtil.getValue("extTL");//通联商户拓展业务字段，在v2.2.0版本之后才使用到的，用于开通分账等业务
		String issuerId=PropertyUtil.getValue("issuerId");
		String pan=PropertyUtil.getValue("pan");
		String tradeNature = PropertyUtil.getValue("tradeNature");
		String sign="";
		
		dto.setServerUrl(serverUrl);
		dto.setVersion(version);
		dto.setLanguage(language);
		dto.setInputCharset(inputCharset);
		dto.setMerchantId(merchantId);
		dto.setPickupUrl(pickupUrl);
		dto.setReceiveUrl(receiveUrl);
		dto.setPayType(payType);
		dto.setSignType(signType);
		dto.setOrderCurrency(orderCurrency);
		dto.setPayerIDCard(payerIDCard);
		dto.setPid(pid);
		dto.setProductId(productId);
		dto.setProductPrice(productPrice);
		dto.setExt1(ext1);
		dto.setExt2(ext2);
		dto.setIssuerId(issuerId);
		dto.setPan(pan);
		dto.setTradeNature(tradeNature);
		//若直连telpshx渠道，payerTelephone、payerName、payerIDCard、pan四个字段不可为空
		//其中payerIDCard、pan需使用公钥加密（PKCS1格式）后进行Base64编码
		if(null!=payerIDCard&&!"".equals(payerIDCard)){
			try{
				//payerIDCard = SecurityUtil.encryptByPublicKey("C:\\TLCert.cer", payerIDCard);   /opt/conf/TLCert.cer
				payerIDCard = SecurityUtil.encryptByPublicKey(ParamsUtil.TLCERT_PATH, payerIDCard);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		if(null!=pan&&!"".equals(pan)){
			try{
				pan = SecurityUtil.encryptByPublicKey(ParamsUtil.TLCERT_PATH, pan);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		//构造订单请求对象，生成signMsg。
		RequestOrder requestOrder=new RequestOrder();
//		com.allinpay.ets.client.RequestOrder requestOrder = new com.allinpay.ets.client.RequestOrder();
		if(null!=inputCharset&&!"".equals(inputCharset)){
			requestOrder.setInputCharset(Integer.parseInt(inputCharset));
		}
		requestOrder.setPickupUrl(pickupUrl);
		requestOrder.setReceiveUrl(receiveUrl);
		requestOrder.setVersion(version);
		if(null!=language&&!"".equals(language)){
			requestOrder.setLanguage(Integer.parseInt(language));
		}
		requestOrder.setSignType(Integer.parseInt(signType));
		requestOrder.setPayType(Integer.parseInt(payType));
		requestOrder.setIssuerId(issuerId);
		requestOrder.setMerchantId(merchantId);
		requestOrder.setPayerName(payerName);
		requestOrder.setPayerEmail(payerEmail);
		requestOrder.setPayerTelephone(payerTelephone);
		requestOrder.setPayerIDCard(payerIDCard);
		requestOrder.setPid(pid);
		requestOrder.setOrderNo(orderNo);
		requestOrder.setOrderAmount(Long.parseLong(orderAmount));
		requestOrder.setOrderCurrency(orderCurrency);
		requestOrder.setOrderDatetime(orderDatetime);
		requestOrder.setOrderExpireDatetime(orderExpireDatetime);
		requestOrder.setProductName(productName);
		if(null!=productPrice&&!"".equals(productPrice)){
			requestOrder.setProductPrice(Long.parseLong(productPrice));
		}
		if(null!=productNum&&!"".equals(productNum)){
			requestOrder.setProductNum(Integer.parseInt(productNum));
		}	
		requestOrder.setProductId(productId);
		requestOrder.setProductDesc(productDesc);
		requestOrder.setExt1(ext1);
		requestOrder.setExt2(ext2);
		requestOrder.setExtTL(extTL);//通联商户拓展业务字段，在v2.2.0版本之后才使用到的，用于开通分账等业务
		requestOrder.setPan(pan);
		requestOrder.setTradeNature(tradeNature);
		requestOrder.setKey(key); //key为MD5密钥，密钥是在通联支付网关会员服务网站上设置。

		String strSrcMsg = requestOrder.getSrc(); // 此方法用于debug，测试通过后可注释。
		String strSignMsg = requestOrder.doSign(); // 签名，设为signMsg字段值。
		dto.setSignMsg(strSignMsg);
	}
	public static String searchOrder(Order order, String sn, String token){
		String signSrc="";
//		String serverUrl=PropertyUtil.getValue("serverUrl");
//		String receiveUrl=PropertyUtil.getValue("receiveUrl");
//		receiveUrl+=token;
//		String key=PropertyUtil.getValue("key"); 
//		String merchantId=PropertyUtil.getValue("merchantId");
//		String version=PropertyUtil.getValue("version");
//		String signType=PropertyUtil.getValue("signType");
//		String orderNo=sn;
//		String orderDatetime=DateTime.timeToString(order.getCreateDate());
//		String queryDatetime=DateTime.timeToString(new Date());
//		
//		StringBuffer bufSignSrc=new StringBuffer();
//		com.allinpay.ets.client.StringUtil.appendSignPara(bufSignSrc, "merchantId",merchantId);
//		com.allinpay.ets.client.StringUtil.appendSignPara(bufSignSrc, "version", version);
//		com.allinpay.ets.client.StringUtil.appendSignPara(bufSignSrc, "signType", signType);
//		com.allinpay.ets.client.StringUtil.appendSignPara(bufSignSrc, "orderNo", orderNo);
//		com.allinpay.ets.client.StringUtil.appendSignPara(bufSignSrc, "orderDatetime",orderDatetime);
//		com.allinpay.ets.client.StringUtil.appendSignPara(bufSignSrc, "queryDatetime",queryDatetime);
//		com.allinpay.ets.client.StringUtil.appendLastSignPara(bufSignSrc, "key", key);
//		signSrc=bufSignSrc.toString();
//		String sign="";
//		sign= com.allinpay.ets.client.SecurityUtil.MD5Encode(bufSignSrc.toString());
//		String signMsg=sign;
//		// 提交查询请求
//		boolean isSuccess = false;
//		String resultMsg = "";
//		Map<String, String> result = new HashMap<String, String>();
//		try{
//			String listenUrl=serverUrl;
//			HttpClient httpclient=new HttpClient();
//			PostMethod postmethod=new PostMethod(listenUrl);
//			NameValuePair[] date = { new NameValuePair("merchantId",merchantId),
//					new NameValuePair("version",version),
//					new NameValuePair("signType",signType),
//					new NameValuePair("orderNo",orderNo),
//					new NameValuePair("orderDatetime",orderDatetime),
//					new NameValuePair("queryDatetime",queryDatetime),
//					new NameValuePair("signMsg",signMsg)};
//			postmethod.setRequestBody(date);
//			int responseCode=httpclient.executeMethod(postmethod);
//			System.out.println("responseCode="+responseCode);		
//			
//			if(responseCode == HttpURLConnection.HTTP_OK){
//				String strResponse = postmethod.getResponseBodyAsString();
//				
//				// 解析查询返回结果
//				strResponse = URLDecoder.decode(strResponse,"gbk");
//			//	Map<String, String> result = new HashMap<String, String>();
//				String[] parameters = strResponse.split("&");
//				for (int i = 0; i < parameters.length; i++) {
//					String msg = parameters[i];
//					int index = msg.indexOf('=');
//					if (index > 0) {
//						String name = msg.substring(0, index);
//						String value = msg.substring(index + 1);
//						result.put(name, value);
//					}
//				}
//		
//				// 查询结果会以Server方式通知商户(同支付返回)；
//				// 若无法取得Server通知结果，可以通过解析查询返回结果，更新订单状态(参考如下).
//				if (null != result.get("ERRORCODE")) {
//					// 未查询到订单
//					System.out.println("ERRORCODE=" + result.get("ERRORCODE"));
//					System.out.println("ERRORMSG=" + result.get("ERRORMSG"));
//					resultMsg = result.get("ERRORMSG");
//		
//				} else {
//					// 查询到订单
//					String payResult = result.get("payResult");
//					if (payResult.equals("1")) {
//						System.out.println("订单付款成功！");
//		
//						// 支付成功，验证签名
//						PaymentResult paymentResult = new PaymentResult();
//						paymentResult.setMerchantId(result.get("merchantId"));
//						paymentResult.setVersion(result.get("version"));
//						paymentResult.setLanguage(result.get("language"));
//						paymentResult.setSignType(result.get("signType"));
//						paymentResult.setPayType(result.get("payType"));
//						paymentResult.setIssuerId(result.get("issuerId"));
//						paymentResult.setPaymentOrderId(result
//								.get("paymentOrderId"));
//						paymentResult.setOrderNo(result.get("orderNo"));
//						paymentResult.setOrderDatetime(result
//								.get("orderDatetime"));
//						paymentResult.setOrderAmount(result.get("orderAmount"));
//						paymentResult.setPayAmount(result.get("payAmount"));
//						paymentResult.setPayDatetime(result.get("payDatetime"));
//						paymentResult.setExt1(result.get("ext1"));
//						paymentResult.setExt2(result.get("ext2"));
//						paymentResult.setPayResult(result.get("payResult"));
//						paymentResult.setErrorCode(result.get("errorCode"));
//						paymentResult.setReturnDatetime(result
//								.get("returnDatetime"));
//						paymentResult.setKey(key);
//						paymentResult.setSignMsg(result.get("signMsg"));
//						paymentResult.setCertPath("/Users/sean/desktop/tlcert/TLCert-test.cer");
////						paymentResult.setCertPath("d:\\cert\\TLCert-test.cer");
//		
//						boolean verifyResult = paymentResult.verify();
//		
//						if (verifyResult) {
//							System.out.println("验签成功！商户更新订单状态。");
//							resultMsg = "订单支付成功，验签成功！商户更新订单状态。";
//							isSuccess = true;
//						} else {
//							System.out.println("验签失败！");
//							resultMsg = "订单支付成功，验签失败！";
//						}
//		
//					} else {
//							System.out.println("订单尚未付款！");
//							resultMsg = "订单尚未付款！";
//					}
//				}
//		
//			}
//		}catch(Exception e){
//		 	e.printStackTrace();
//		}
//		return resultMsg;
		return signSrc;
	}
}
